# -*- coding: utf-8 -*-
from pymongo import MongoClient
from datetime import datetime
import time
import global_var

from bson.objectid import ObjectId

log = global_var.gl_log

#转换mongodb _id的时间戳
def timestamp_from_objectid(objectid):
    result = 0
    try:
        result = time.mktime(objectid.generation_time.timetuple())
    except:
        pass
    return result

def objectid_from_datetime(from_datetime=None):
    ''' According to the time manually generated an ObjectId '''
    if not from_datetime:
        from_datetime = datetime.datetime.now()
    return ObjectId.from_datetime(generation_time=from_datetime)

#读写配置文件信息
class CDBConfig:
    db = None
    def __init__(self,db_addr="127.0.0.1",db_port=27017,db_name="mydb",tb_name="gConf"):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.tb_name = tb_name

        try:
            self.conn = MongoClient(self.db_addr, self.db_port)
            self.db = self.conn[self.db_name]
        except Exception as e:
            log.error("connect db [{}] err {}".format(db_name, e))

    def read(self, conf_name):
        qry = {"conf_name":"{}".format(conf_name)}
        ret_find = self.db[self.tb_name].find_one(qry)
        if ret_find:
            return ret_find["conf_val"]
        else:
            return None

    def write(self, conf_name, conf_val):
        try:
            qry = {"conf_name":"{}".format(conf_name)}
            ins_vals = None
            ins_vals = {"conf_name":"{}".format(conf_name), "conf_val":conf_val} 
            if self.db[self.tb_name].find_one(qry):
                upd_qry = {"$set":ins_vals}
                self.db[self.tb_name].update_one(qry,upd_qry)
            else:
                self.db[self.tb_name].insert_one(ins_vals)

        except Exception as e:
            log.error("write err: {}".format( e))
    
    def close(self):
        self.conn.close()
        

class CDBProcessor:
    db = None
    def __init__(self,db_addr="127.0.0.1", db_port=27017, db_name="mydb"):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        
        

    def connect(self):
        try:
            self.conn = MongoClient(self.db_addr, self.db_port)
            if self.db_name==None or len(self.db_name)==0:
                self.db = None
            else:
                self.db = self.conn[self.db_name]
            
        except Exception as e:
            log.error("connect db err {}".format(e))

    #open table name
    def open(self, tbl_name):
        pass

    #insert data type: list(multiple record) or dict(one record)
    def insert(self,tbl_name, ins_vals):
        result = []
        try:
            if self.db == None or tbl_name==None or len(tbl_name)==0:
                pass
            else:
                if isinstance(ins_vals, list):
                    ret = self.db[tbl_name].insert_many(ins_vals)
                    result = ret.inserted_ids
                elif isinstance(ins_vals, dict):
                    ret = self.db[tbl_name].insert_one(ins_vals)
                    result.append(ret.inserted_id)
        except Exception as e:
            log.error("insert data err: {}".format( e))
        #print("return: ", result)
        
        return result
    
    def find(self, tbl_name, qry_option):
        ret = 0# 0 - not find , 1 - find
        try:
            ret_find = self.db[tbl_name].find(qry_option)
            if ret_find:
                ret=1
        except Exception as e:
            log.error("find err: {}".fpriniormat(e))
        
        return ret

    def findmany(self, tbl_name, qry_option):
        ret = []
        try:
            rlt = self.db[tbl_name].find(qry_option)

            for it in rlt:
                ret.append(it)
                # log.info("plate[{}]".format(it["plate_id"]))

            #log.info("find: [{}] record".format(ret.count()))
        except Exception as e:
            log.error("find err: {}".format(e))
        
        return ret
    
    def findone(self, tbl_name, dic_query):
        ret = None
        try:
            ret = self.db[tbl_name].find_one(dic_query)
            
        except Exception as e:
            pass

        return ret

    def update(self, tbl_name, id_val, upd_vals):
        try:
            myquery={"_id":id_val}
            newvals = {"$set":upd_vals}
            ret = self.db[tbl_name].update_one(myquery, newvals)
            #print("update ret = ", ret, "\ntimestamp: ", timestamp_from_objectid(id_val))

        except Exception as e:
            log.error("udpate err: {}".format( e))
        

    def disconnect(self):
        self.conn.close()
